package com.xl.basic.utils;


import cn.hutool.extra.servlet.JakartaServletUtil;

import com.xl.basic.entity.Result;

import jakarta.servlet.http.HttpServletRequest;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import lombok.NonNull;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * ServletUtils工具的包装
 *
 * @author 钟勇
 * Create in 2023/8/23 13:07
 */

public class ServletUtils {

    /**
     * 获取HttpServletRequest
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return requestAttributes.getRequest();
    }

    /**
     * 获取HttpServletResponse
     *
     * @return HttpServletResponse
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return requestAttributes.getResponse();
    }

    /**
     * 获取当前客服端ip
     *
     * @return ip
     */
    public static String getClientIP() {
        HttpServletRequest request = getRequest();
        String ip = JakartaServletUtil.getClientIP(request);
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        return ip;
    }

    /**
     * 获取session
     *
     * @return session
     */
    public static HttpSession getSession() {
        HttpServletRequest request = getRequest();
        return request.getSession();
    }

    /**
     * 写出json格式的返回
     *
     * @param res res对象
     * @param <T> T
     */
    public static <T> void write(@NonNull Result<T> res) {
        HttpServletResponse response = getResponse();
        JakartaServletUtil.write(response, res.toString(), "application/json");
    }
}
